﻿using System.Linq;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class InputHandler : MonoBehaviour {
	private Dictionary<int, Touchable> lingers = new Dictionary<int, Touchable>();
    public Camera oCamera;

    void Start() {
        oCamera = oCamera ?? Camera.allCameras.First(c => c != Camera.main);
    }
	void Update() {
		foreach(var touch in Input.touches) {
			// Construct a ray from the current touch coordinates
			var ray = oCamera.ScreenPointToRay (new Vector3(touch.position.x, touch.position.y, -60));
			RaycastHit hit;
            if(lingers.ContainsKey(touch.fingerId)) {
                lingers[touch.fingerId].TouchUpdate(touch);
            } else if(Physics.Raycast(ray, out hit)) {
				// Create a particle if hit
				var comp = hit.collider.gameObject.GetComponent<Touchable>();
				if(comp != null) {
					comp.TouchUpdate(touch);
					if(!lingers.ContainsKey(touch.fingerId))
						lingers.Add(touch.fingerId, comp);
				}
			}
		}
	}

	void LateUpdate() {
		foreach(var touch in Input.touches) {
			if(touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) {
				if(lingers.ContainsKey(touch.fingerId)) {
					lingers[touch.fingerId].TouchEnd(touch);
					lingers.Remove(touch.fingerId);	
				}
			}
		}
	}
}
